/**
 * $Revision: $
 * $Date: $
 *
 * Copyright (C) 2005-2008 Jive Software. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.lastcoder.ifserver.nio;

import net.lastcoder.ifserver.Globals;
import net.lastcoder.ifserver.Server;
import net.lastcoder.ifserver.packet.Event;
import net.lastcoder.ifserver.packet.Packet;
import net.lastcoder.ifserver.packet.PingHandler;
import net.lastcoder.ifserver.route.EventHandlerManager;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class ClientConnectionHandler extends ConnectionHandler {

	private static final Logger Log = LoggerFactory.getLogger(ClientConnectionHandler.class);

    private static Event sPingEvent = new Event(Event.PING_EVENT_TYPE, Packet.TYPE_SET, 0);
    private static byte[] sBuffer;
    private static boolean sDoPing = true;
    private static int sIdleTime = 2 * 60 * 1000;
    private PingHandler pingHandler = new PingHandler();

    public ClientConnectionHandler() {
        EventHandlerManager eventHandlerManager = EventHandlerManager.getInstance();
        eventHandlerManager.putEventHandler(pingHandler);
        sPingEvent.setFromAddress(Server.getInstance().getServerId());
        sBuffer = sPingEvent.getRawData();
        sDoPing = Globals.getXMLProperty("client.session.idle.ping", true);

        sIdleTime = Globals.getXMLProperty("client.session.idle.time", 2 * 60 * 1000) / 1000;
    }

    @Override
	NIOConnection createNIOConnection(IoSession session) {
        return new NIOConnection(session);
    }

    @Override
	int getMaxIdleTime() {
        return sIdleTime;
    }
    @Override
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
    	super.sessionIdle(session, status);
    	
        if (sDoPing && session.getIdleCount(status) == 1) {
			final Connection connection = (Connection) session.getAttribute(CONNECTION);

            if (connection != null && !connection.isClosed()) {
                connection.deliverRawData(sBuffer);
            }
        }
    }
}
